<template>
  <div
    class="el-tree-node"
    @click.stop="handleClick"
    @contextmenu="($event) => this.handleContextMenu($event)"
    v-show="node.visible"
    :class="{
      'is-expanded': expanded,
      'is-hidden': !node.visible,
      'is-focusable': !node.disabled,
      'is-checked': !node.disabled && node.checked
    }"
    role="treeitem"
    tabindex="-1"
    :aria-expanded="expanded"
    :aria-disabled="node.disabled"
    :aria-checked="node.checked"
    @dragstart.stop="handleDragStart"
    @dragover.stop="handleDragOver"
    @dragend.stop="handleDragEnd"
    @drop.stop="handleDrop"
    ref="node"
  >
    <div class="el-tree-node__content"
      :style="{ 'padding-left': (node.level - 1) * 12 + 'px' }">
      <span
        class="el-tree-node__expand-icon el-icon-caret-right"
        @click.stop="handleExpandIconClick"
        :class="{ 'is-leaf': node.isLeaf, expanded: !node.isLeaf && expanded }">
      </span>
      <el-checkbox
        v-if="showCheckbox"
        v-model="node.checked"
        :indeterminate="node.indeterminate"
        :disabled="!!node.disabled"
        @click.native.stop
        @change="handleCheckChange"
      >
      </el-checkbox>
      <span
        v-if="node.loading"
        class="el-tree-node__loading-icon el-icon-loading">
      </span>
      <node-content :node="node"></node-content>
    </div>
    <div
      class="el-tree-node__children"
      v-if="!renderAfterExpand || childNodeRendered"
      v-show="expanded"
      role="group"
      :aria-expanded="expanded"
    >
      <ShowIndexRange :tree="tree"
        :style="{
          position: 'relative',
          height: itemheight * (maxShowIndex - node.showIndex) + 'px'
        }"
      >
        <el-tree-node
          v-for="child in node.childNodes"
          :style="{
            position: 'absolute',
            width: '100%',
            top: (child.showIndex - node.showIndex - 1) * itemheight + 'px'
          }"
          :show-index="child.showIndex"
          :need-filter="child.isLeaf"
          :render-content="renderContent"
          :render-after-expand="renderAfterExpand"
          :key="getNodeKey(child)"
          :node="child"
          @node-expand="handleChildNodeExpand">
        </el-tree-node>
      </ShowIndexRange>
    </div>
  </div>
</template>

<script lang="tsx">
import { Component, Prop, Vue, Inject, Mixins, Watch } from 'vue-property-decorator';
import { getNodeKey } from './model/util.js'
import Emitter from '../polyfill/emitter'
import ShowIndexRange from './ShowIndexRange.vue'
@Component({
  name: 'ElTreeNode',
  components: {
    ShowIndexRange,
    NodeContent: {
      props: {
        node: {
          required: true
        }
      },
      render (h) {
        const parent: any = this.$parent
        const tree: any = parent.tree || {}
        const node: any = (this as any).node || {}
        const { data, store } = node
        return (
          parent.renderContent
            ? parent.renderContent.call(parent._renderProxy, h, { _self: tree.$vnode.context, node, data, store })
            : tree.$scopedSlots && tree.$scopedSlots.default
              ? tree.$scopedSlots.default({ node, data })
              : h(
                  'span',
                  {
                    class: {
                      'el-tree-node__label': true
                    }
                  },
                  [node.label] //  + ' showIndex ' + node.showIndex
                )
        )
      }
    }
  }
})
export default class ElTreeNode extends Mixins(Emitter) {
  @Inject('ranger') private ranger
  @Inject('itemheight') private itemheight
  @Prop() private node: any
  @Prop() private props: any
  @Prop() private renderContent: any
  @Prop({ default: true}) private renderAfterExpand: any
  get maxShowIndex () {
    return this.node.maxShowIndex
  }
  private tree: any = null
  private expanded = false
  private childNodeRendered = false
  private showCheckbox = false
  private oldChecked: any = false
  private oldIndeterminate = null

  private getNodeKey (node: any) {
    if (this.tree && this.tree.nodeKey) {
      return getNodeKey(this.tree.nodeKey, node.data)
    }
  }

  private  handleSelectChange (checked: any, indeterminate: any) {
    if (this.oldChecked !== checked && this.oldIndeterminate !== indeterminate) {
      this.tree.$emit('check-change', this.node.data, checked, indeterminate)
    }
    this.oldChecked = checked
    // this.indeterminate = indeterminate
  }

   private handleClick () {
      const store = this.tree.store
      if (store) {
        store.setCurrentNode(this.node)
        this.tree.$emit('current-change', store.currentNode ? store.currentNode.data : null, store.currentNode)
        this.tree.currentNode = this
        if (this.tree.expandOnClickNode) {
          this.handleExpandIconClick()
        }
        if (this.tree.checkOnClickNode) {
          this.handleCheckChange(null, {
            target: { checked: !this.node.checked }
          })
        }
        this.tree.$emit('node-click', this.node.data, this.node, this)
      }
    }

  private  handleContextMenu (event) {
    if (this.tree._events['node-contextmenu'] && this.tree._events['node-contextmenu'].length > 0) {
      event.stopPropagation()
      event.preventDefault()
    }
    this.tree.$emit('node-contextmenu', event, this.node.data, this.node, this)
  }

  private  handleExpandIconClick () {
    if (this.node.isLeaf) {
      return
    }
    if (this.expanded) {
      this.tree.$emit('node-collapse', this.node.data, this.node, this)
      this.node.collapse()
    } else {
      this.node.expand()
      this.$emit('node-expand', this.node.data, this.node, this)
    }
  }

  private  handleCheckChange (value, ev) {
      this.node.setChecked(ev.target.checked, !this.tree.checkStrictly)
      this.$nextTick(() => {
        this.tree.$emit('check', this.node.data, {
          checkedNodes: this.tree.store.getCheckedNodes(),
          checkedKeys: this.tree.store.getCheckedKeys(),
          halfCheckedNodes: this.tree.store.getHalfCheckedNodes(),
          halfCheckedKeys: this.tree.store.getHalfCheckedKeys()
        })
      })
    }

  private  handleChildNodeExpand (nodeData, node, instance) {
    this.dispatchEmitter('ElTreeNode', 'tree-node-expand', node)
    this.tree.$emit('node-expand', nodeData, node, instance)
  }

  private  handleDragStart (event) {
    if (!this.tree && !this.tree.draggable) {
      return
    }
    this.tree.$emit('tree-node-drag-start', event, this)
  }

  private  handleDragOver (event) {
    if (!this.tree && !this.tree.draggable) {
      return
    }
    this.tree.$emit('tree-node-drag-over', event, this)
    event.preventDefault()
  }

  private  handleDrop (event) {
      event.preventDefault()
    }

  private  handleDragEnd (event) {
    if (!this.tree && !this.tree.draggable) { 
      return
    }
    this.tree.$emit('tree-node-drag-end', event, this)
  }

  @Watch('node.indeterminate', { immediate: true, deep: true })
  private indeterminateChange (newValue) {
    this.handleSelectChange(this.node.checked, newValue)
  }
  @Watch('node.checked', { immediate: true, deep: true })
  private checkedChange (newValue, old) {
    // this.handleSelectChange(newValue, this.node.indeterminate)
  }
  @Watch('node.expanded', { immediate: true, deep: true })
  private expandedChange (newValue) {
    this.$nextTick(() => { this.expanded = newValue })
    if (newValue) {
      this.childNodeRendered = true
    }
  }

  private mounted () {
    const parent: any = this.$parent
    if (parent.isTree) {
      this.tree = parent
    } else {
      this.tree = parent.tree
    }

    const tree = this.tree || {}
    if (!tree) {
      console.warn('Can not find node\'s tree.')
    }

    const props = tree && tree.props || {}
    // eslint-disable-next-line no-mixed-operators
    const childrenKey = props['children'] || 'children'
    this.$watch(`node.data.${childrenKey}`, () => {
      this.node.updateChildren()
    })
    this.showCheckbox = tree.showCheckbox
    if (this.node.expanded) {
      this.expanded = true
      this.childNodeRendered = true
    }
    if (this.tree && this.tree.accordion) {
      this.$on('tree-node-expand', node => {
        if (this.node !== node) {
          this.node.collapse()
        }
      })
    }
  }
}
</script>
